//
//  LoginViewController.m
//  IceBreaker
//
//  Created by Chiao Wolfire on 12-10-3.
//  Copyright (c) 2012年 NDS. All rights reserved.
//

#import "LoginViewController.h"
#import "TabsViewController.h"
#import "PublicUtils.h"
#import "NSData+Base64.h"
#import "User.h"
#import "UserDetailViewController.h"

@implementation LoginViewController

@synthesize mySocket;
@synthesize serverIP;
@synthesize connectPort;
@synthesize connectTime;

@synthesize mailLabel, pwdLabel;
@synthesize mailTxt, pwdTxt;
@synthesize loginBtn, registerBtn;

-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    NSLog(@"initWithNibName");
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.title = NSLocalizedStringFromTable(@"Log in", @"Localizable", @"Log in");
        // read configuration from bundle
        serverIP = [[NSUserDefaults standardUserDefaults] stringForKey: @"connectHost"];
        connectPort = [[NSUserDefaults standardUserDefaults] integerForKey: @"connectPort"];
        connectTime = [[NSUserDefaults standardUserDefaults] doubleForKey: @"connectTimeout"];
        NSLog(@"Configuration read: HOST:[%@], PORT:[%d], TIMEOUT:[%f]", serverIP, connectPort, connectTime);
    }
    return self;
}

-(void) viewWillAppear:(BOOL)animated {
    NSLog(@"viewWillAppear");
}

-(void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [[UIApplication sharedApplication] setStatusBarHidden: NO withAnimation: UIStatusBarAnimationSlide];
    [mailLabel setText: NSLocalizedStringFromTable(@"Mail box", @"Localizable", @"Mail box")];        
    [pwdLabel setText: NSLocalizedStringFromTable(@"Password", @"Localizable", @"Password")];
    [mailTxt setPlaceholder: NSLocalizedStringFromTable(@"Input mail", @"Localizable", @"Please input your mail box")];
    [mailTxt setDelegate: self];
    [pwdTxt setPlaceholder: NSLocalizedStringFromTable(@"Input pwd", @"Localizable", @"Please input your password")];
    [pwdTxt setDelegate: self];
    pwdTxt.secureTextEntry = YES;
    [loginBtn setTitle: NSLocalizedStringFromTable(@"Log in", @"Localizable", @"Log in") 
              forState: UIControlContentHorizontalAlignmentCenter];
    [registerBtn setTitle: NSLocalizedStringFromTable(@"Register", @"Localizable", @"Log in")
                 forState: UIControlContentHorizontalAlignmentCenter];
    
    NSLog(@"~~~~~%@~~~~~~%d~~~~~~%f~~~~~~", serverIP, connectPort, connectTime);
    
    [self createConnection: serverIP
                      port: connectPort
                   timeout: connectTime];
}

-(void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    mailLabel = nil;
    pwdLabel = nil;
    mailTxt = nil;
    pwdTxt = nil;
    loginBtn = nil;
    registerBtn = nil;
    self.mySocket = nil;
}

-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark -instance methods
-(IBAction) buttonTouched:(id)sender {
    if (mailTxt.text == nil || [mailTxt.text isEqualToString: @""]) {
        [PublicUtils alertMsgWithTitle: NSLocalizedStringFromTable(@"Alert tips", @"Localizable", @"Tips") 
                               message: @"邮箱不能为空！" 
                     cancelButtonTitle: NSLocalizedStringFromTable(@"Confirm text", @"Localizable", @"OK")];

        [mailTxt becomeFirstResponder];
        return;
    }
    if (pwdTxt.text == nil || [pwdTxt.text isEqualToString: @""]) {
        [PublicUtils alertMsgWithTitle: NSLocalizedStringFromTable(@"Alert tips", @"Localizable", @"Tips") 
                               message: @"密码不能为空！" 
                     cancelButtonTitle: NSLocalizedStringFromTable(@"Confirm text", @"Localizable", @"OK")];

        [pwdTxt becomeFirstResponder];
        return;
    }

    switch ([sender tag]) {
        case 0:
            [self registerAction];
            break;
        case 1:
            [self loginAction];
            break;
        default:
            break;
    }
    
}

-(void) loginAction {
    NSData *codeData = [@"M1" dataUsingEncoding: NSUTF8StringEncoding];
    NSString *encodedCode = [NSData encodeBase64: codeData];
    NSData *mailData = [mailTxt.text dataUsingEncoding: NSUTF8StringEncoding];
    NSString *encodedMail = [NSData encodeBase64: mailData];
    NSData *pwdData = [pwdTxt.text dataUsingEncoding: NSUTF8StringEncoding];
    NSString *encodedPwd = [NSData encodeBase64: pwdData];
    
    NSString *sendStr = [encodedCode stringByAppendingString: @";"];
    sendStr = [sendStr stringByAppendingString: encodedMail];
    sendStr = [sendStr stringByAppendingString: @";"];
    sendStr = [sendStr stringByAppendingString: encodedPwd];
    sendStr = [sendStr stringByAppendingString: @";\r\n"];
    NSLog(@"String to be send~~~~%@~~~~", sendStr);

    NSData *dataToSend = [sendStr dataUsingEncoding: NSUTF8StringEncoding];
    [self sendData: dataToSend
           timeout: connectTime];

    TabsViewController *tabs = [[TabsViewController alloc] init];
    [self presentModalViewController: tabs animated:YES];
}

-(void) registerAction {
    User *user = [[User alloc] initWithMailBox: mailTxt.text
                                      password: pwdTxt.text];
    UserDetailViewController *userDetail = [[UserDetailViewController alloc] initWithNibName: @"UserDetailViewController"
                                                                                      bundle: nil];
    userDetail.user = user;
    [self presentModalViewController: userDetail
                            animated: YES];
}

// touch the view to close the keyboard
-(IBAction)closeViewEdit:(id)sender {
    [mailTxt resignFirstResponder];
    [pwdTxt resignFirstResponder];
    self.view.center = CGPointMake(160, 250);
}

-(BOOL) textFieldShouldBeginEditing:(UITextField *)textField {
    // the original coordination of the screen is (160, 250)
    // up it to make the text feild visible
    switch ([textField tag]) {
        case 0:
            self.view.center = CGPointMake(160, 240);
            break;
        case 1:
            self.view.center = CGPointMake(160, 210);
            break;
            
        default:
            break;
    }

    return YES;
}

-(BOOL) textFieldShouldReturn:(UITextField *)textField {  
    self.view.center = CGPointMake(160, 250);
    switch ([textField tag]) {
        case 0:
            [mailTxt resignFirstResponder];
            break;
        case 1:
            [pwdTxt resignFirstResponder];
            // no longer login defaultly
            // [self buttonTouched: loginBtn];
            break;
        default:
            break;
    }
    return YES;
}

#pragma mark
#pragma mark - Socket delegate
-(int) createConnection: (NSString *)hostIP
                   port: (UInt16)hostPort
                timeout: (NSTimeInterval)timeout{
    if (self.mySocket == nil) {
        self.mySocket = [[AsyncSocket alloc] initWithDelegate: self];
        NSError *err = nil;

        if (![mySocket connectToHost: hostIP
                              onPort: hostPort
                         withTimeout: timeout
                               error: &err]) {
            NSLog(@"Something wrong with the connection, error code is [%d] and the error reads [%@]. Please check the network.", [err code], [err localizedDescription]);;
            return CONNECTION_FAIL;
        } else {
            NSLog(@"Connection OK");
            return CONNECTION_SUC;
        }
    } else {
        /*
        [mySocket readDataWithTimeout: -1 tag: 0];
        */
        return SRV_CONNECTED;
    }
}

-(IBAction)reConnect:(NSString *)hostIP
                port:(UInt16)hostPort
             timeout:(NSTimeInterval)timeout{
    NSLog(@"Trying to reconnect to the server, the host is [%@] while the port is [%d]", hostIP, hostPort);
    int stateCode = [self createConnection: hostIP
                                      port: hostPort
                                   timeout: timeout];
    switch (stateCode) {
		case SRV_CONNECTED:
			break;
		case CONNECTION_SUC:
			break;
        case CONNECTION_FAIL:
            break;
		default:
			break;
	}
}

-(IBAction) sendData:(NSData *)dataToSend
             timeout:(NSTimeInterval)timeout {
    NSLog(@"Start to send data to the server [%@], the data is [%@]", serverIP, dataToSend);
    [mySocket writeData: dataToSend
            withTimeout: timeout
                    tag: 0];
}

#pragma mark socket delegate

- (void)onSocket:(AsyncSocket *)sock
didConnectToHost:(NSString *)host
            port:(UInt16)port{
	[mySocket readDataWithTimeout: -1
                              tag: 0];
}

- (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle: [NSString stringWithFormat:@"Error %d", [err code]]
                                                    message: [NSString stringWithFormat:@"The connection failed, %@", [err localizedDescription]]
                                                   delegate: nil
                                          cancelButtonTitle: @"OK"
                                          otherButtonTitles: nil];
    [alert show];
    [alert release];
    NSLog(@"Error!!!!");
}

- (void)onSocketDidDisconnect:(AsyncSocket *)sock {
	NSLog(@"Sorry this connect is failure");
    [mySocket disconnect];
	mySocket = nil;
}

- (void)onSocketDidSecure:(AsyncSocket *)sock{
    
}

-(void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag {
    NSLog(@"thread(%@),onSocket:%p didWriteDataWithTag:%ld",[[NSThread currentThread] name], sock, tag);
}

- (void)onSocket: (AsyncSocket *)sock
     didReadData: (NSData *)data
         withTag: (long)tag{
    NSLog(@"Data read from server is [%@]", data);
	NSString* readStr = [[NSString alloc] initWithData: data
                                           encoding: NSUTF8StringEncoding];
	NSLog(@"Parse the data recieved a string [%@]",readStr);
	[mySocket readDataWithTimeout: -1
                              tag: 0];
    
    NSArray *responseData = [readStr componentsSeparatedByString: @";"];
    NSMutableArray *temArray = nil;
    for (NSString *str in responseData) {
        [temArray addObject: [[[NSString alloc] initWithData: [NSData decodeBase64: str]
                                                    encoding: NSUTF8StringEncoding] autorelease]];
    }
    NSArray *responseStrings = temArray;
    if (responseStrings) {
        for (NSString *str in responseStrings) {
            NSLog(@"~~~~%@~~~~", str);
        }
    }
}

@end
